<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->

    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="rolesAdd">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表数据 -->
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{scope.row}}
                     -->
            <el-row
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  @close="removeRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级 -->
              <el-col :span="19">
                <!-- 通过for嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeRightById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      @close="removeRightById(scope.row, item3.id)"
                      closable
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑用户对话框 -->
            <el-dialog
              title="修改用户"
              :visible.sync="editDialogVisible1"
              width="50%"
            >
              <el-form ref="showfromRef" :model="showfrom" label-width="70px">
                <el-form-item label="角色id">
                  <el-input v-model="showfrom.roleId" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色名称">
                  <el-input v-model="showfrom.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                  <el-input v-model="showfrom.roleDesc"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="editUsershow(scope.row.id)"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
            <el-button
              size="min"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="min"
              type="danger"
              icon="el-icon-delete"
              @click="removeIdInfo(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="min"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setTightDialogClosed"
    >
    <!-- 树形控件 -->
      <el-tree :data="rightslist" node-key="id" default-expand-all :props="treeProps" show-checkbox 
        :default-checked-keys="defKeys" ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editfromRef" :model="editfrom" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editfrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editfrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色信息
      rolelist: [],
      editDialogVisible: false,
      editfrom: {},
      showfrom: {},
      editDialogVisible1: false,
      setRightDialogVisible:false,
      rightslist:[],
      roleId:null,//获取当前点击分配权限的id
      //树形控件绑定对象
      treeProps:{
        label:'authName',
        children:'children',
      },
        defKeys:[]//选中节点的地址

    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    look() {},
    // 获取所有角色数据列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取信息失败");
      }
      this.rolelist = res.data;
    },
    //监听添加表单的出现
    rolesAdd() {
      this.editDialogVisible = !this.editDialogVisible;
    },
    //添加表单提交数据
    async editUserInfo() {
      const { data: res } = await this.$http.post("/roles", {
        roleName: this.editfrom.roleName,
        roleDesc: this.editfrom.roleDesc,
      });
      if (res.meta.status != 201) {
        return this.$message.error("添加失败");
      }
      this.getRolesList();
      this.editDialogVisible = !this.editDialogVisible;
      this.$message.success("添加成功");
    },
    //监听删除
    async removeIdInfo(id) {
      // console.log(id);
      //   const {data:res} = await this.$http.delete("/roles/"+id)
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
      if (res == "confirm") {
        const { data: resInfo } = await this.$http.delete("/roles/" + id);
        if (resInfo != 200) {
          this.$message.error("删除失败");
        }
        this.getRolesList();
        this.$message.success("删除成功");
      }
    },
    // 监听编辑
    async showEditDialog(id) {
      // console.log(id);
      this.editDialogVisible1 = !this.editDialogVisible1;
      const { data: res } = await this.$http.get("/roles/" + id);
      //    console.log(res);
      this.showfrom = res.data;
    },
    async editUsershow(id) {
      const { data: res } = await this.$http.put("/roles/" + id, this.showfrom);
      this.editDialogVisible1 = !this.editDialogVisible1;
      if (res.meta.status != 200) {
        return this.$message.error("修改失败");
      }
      this.$message.success("修改成功");
      this.getRolesList();
    },
    //根据ID删除对应的权限
    async removeRightById(role, rightId) {
      //弹框提示用户是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult != "confirm") {
        return this.$message.info("取消了删除");
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      // this.getRolesList()
      role.children = res.data;
    },
    //展示分配权限的对话框
   async showSetRightDialog(role) {

     this.roleId = role.id
      //获取所有权限的数据
    const {data:res}= await this.$http.get('rights/tree')

      if(res.meta.status!=200){
        return this.$message.error("获取失败")
      }
      //获取到的权限数据保存到data中
      this.rightslist =res.data

      this.getLeafKeys(role,this.defKeys)


      this.setRightDialogVisible=true

    },
    // 通过递归来获取所有三级权限下得id
    getLeafKeys(node,arr){

      if(!node.children){
        return arr.push(node.id)
      }

      node.children.forEach(item=>this.getLeafKeys(item,arr))

    },
    //监听分配权限对话框关闭事件
    setTightDialogClosed(){
        this.defKeys=[]
    },
    //点击为角色分配权限
  async allotRights(){
        const keys=[...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
        
        ]

        const idStr = keys.join(',')
     const {data:res}= await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
        })

        if(res.meta.status != 200){
          return this.$message.error('分配权限失败')
        }
        this.$message.success('分配成功')
        this.setRightDialogVisible = false
        this.getRolesList()
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>